package com.lbx.config;

import com.alibaba.fastjson.JSON;
import com.lbx.entity.SysUser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;

/**
 * @author lbx create by 2021/6/10 10:23
 * @apiNote SuccessHandler
 */
@Service
public class SuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication auth) throws IOException {
        SysUser sysUser = (SysUser) auth.getPrincipal();
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginUser", sysUser);
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, "lvbingxing")
                .setClaims(map)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 30))
                .compact();
        response.setHeader("Access-Control-Allow-Origin", "*");
        PrintWriter out = response.getWriter();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", 200);
        hashMap.put("msg", "LoginSuccess!");
        hashMap.put("data", token);
        String jsonString = JSON.toJSONString(hashMap);
        out.print(jsonString);
        out.flush();
        out.close();
    }
}
